﻿using pe.edu.pucp.lp2.controller;
using pe.edu.pucp.lp2.model.bean;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SalesModel;
using System.Windows.Forms;
using SalesApp;

namespace pe.edu.pucp.lp2.sales
{
    class Program
    {
    
    static double curTax = 19;
	
	static void showInvoice(){
		int codCash=0, codCli,accessCode = 0;
		String scan,opcionMenu;

        string pass = "";
        ConsoleKeyInfo key;
		
		do{
            int flag;
            do
            {
                flag = 1;
                try
                {
                    Console.WriteLine("Ingrese el código del usuario:");
                    Console.Write("> ");
                    scan = Console.ReadLine();
                    codCash = Convert.ToInt32(scan);
                }

                catch (FormatException)
                {
                    flag = 0;
                    Console.WriteLine("Error !!!, debes ingresar un dato entero!!!");
                }

            } while (flag == 0);
			
			if( (SalesManager.getCashierById(codCash)==null) && (SalesManager.getManagerById(codCash)==null) )
				Console.WriteLine("ERROR: El codigo de usuario que ingreso, no existe");
		}while((SalesManager.getCashierById(codCash)==null)&&(SalesManager.getManagerById(codCash)==null));//Hasta que un código de store manager o un cajero sea ingresado
		
		if(SalesManager.isInManagerList(codCash)){//Un store manager ha ingresado
			userRole=1;
			Console.WriteLine("Iniciando Sesion como store Manager:"+ 
                               SalesManager.getManagerById(codCash).getName() +" "+
                               SalesManager.getManagerById(codCash).getfLastName() + "...");
		}
		else{ //Un cajero ha ingresado
		    Console.WriteLine("Iniciando Sesion como cajero:"+ 
                               SalesManager.getCashierById(codCash).getName() +" "+
                               SalesManager.getCashierById(codCash).getfLastName() + "...");
		}
		Console.WriteLine("> Por favor, ingrese su contrasena:");
		Console.Write("> ");


        //Ingresa Contrasena Ocultando
        pass = "";
        do
        {
            key = Console.ReadKey(true);

            // Backspace Should Not Work
            if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
            {
                pass += key.KeyChar;
                Console.Write("*");
            }
            else
            {
                if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
                {
                    pass = pass.Substring(0, (pass.Length - 1));
                    Console.Write("\b \b");
                }
            }
        }
        // Stops Receving Keys Once Enter is Pressed
        while (key.Key != ConsoleKey.Enter);
        Console.WriteLine();
        //Fin Ingresa Contrasena Ocultando

		//scan = Console.ReadLine(); 
		int pwInt = Convert.ToInt32(pass);
		
		//pw validation
		int pwCorrect = 0;
		while (pwCorrect!=1){
			if( userRole==0){
				if (pwInt == SalesManager.getCashierById(codCash).getPassword() ){
					pwCorrect=1;
					break;
				}
			}
			else {
				if (pwInt == SalesManager.getManagerById(codCash).getPassword() ){
					pwCorrect=1;
					break;
				}
			}
			Console.WriteLine("> Contrasena incorrecta. Por favor, ingrese su contrasena:");
			Console.Write("> ");
            //Ingresa Contrasena Ocultando
            pass = "";
            do
            {
                key = Console.ReadKey(true);

                // Backspace Should Not Work
                if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                {
                    pass += key.KeyChar;
                    Console.Write("*");
                }
                else
                {
                    if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
                    {
                        pass = pass.Substring(0, (pass.Length - 1));
                        Console.Write("\b \b");
                    }
                }
            }
            // Stops Receving Keys Once Enter is Pressed
            while (key.Key != ConsoleKey.Enter);
            Console.WriteLine();
            //Fin Ingresa Contrasena Ocultando
			//scan = Console.ReadLine(); 
            pwInt = Convert.ToInt32(pass);
			
		}
		
		
		
		
		Console.WriteLine("> Usted se ha loggeado exitosamente.");
		Console.WriteLine("> Bienvenido!");
		Console.WriteLine("=================================================");
		
		int opInt;
		do{
            Console.WriteLine("================================================");
		    if(userRole==0)	

		       Console.WriteLine(SalesManager.getCashierById(codCash).getName()+", Que desea realizar?");
		    else 
			    Console.WriteLine(SalesManager.getManagerById(codCash).getName()+", Que desea realizar?");
		
		    Console.WriteLine("================================================");
		    Console.WriteLine(" (1) Operaciones con cliente");
		    Console.WriteLine(" (2) Operaciones con producto");
            Console.WriteLine(" (3) Operaciones con cajero");
		    Console.WriteLine(" (4) Operaciones con venta");
            Console.WriteLine(" (5) Operaciones con terminal cajero");
		    Console.WriteLine(" (6) Exit");
		    Console.WriteLine("=================================================");
		    Console.Write("> ");
		    opcionMenu=Console.ReadLine();
		    opInt=Convert.ToInt32(opcionMenu);
            String strTelf = "";
		
		  if(opInt==1){ //operaciones con cliente
            int opcionesCliente=0;
            String opcionCliente;
            do{
                Console.WriteLine("================================================");
                Console.WriteLine(" (1) Registrar  cliente");
                Console.WriteLine(" (2) Actualizar cliente");
                Console.WriteLine(" (3) Eliminiar cliente");
                Console.WriteLine(" (4) Terminar");
                Console.WriteLine("=================================================");
                opcionCliente = Console.ReadLine();
                opcionesCliente = Convert.ToInt32(opcionCliente);
                String opcion;
                if (opcionesCliente == 1)
                {
                    do
                    {
                        Console.WriteLine("===REGISTRAR CLIENTE===");
                        Customer cus6 = new Customer();
                        //BufferedReader Console=new BufferedReader(new InputStreamReader(System.in));
                        String strDni, strNombre, strLname, strMname, strDir, strEmail;

                        Console.WriteLine("Dni:");
                        Console.Write("> ");
                        strDni = Console.ReadLine();
                        cus6.setDni(strDni);
                        Console.WriteLine("Nombre:");
                        Console.Write("> ");
                        strNombre = Console.ReadLine();
                        cus6.setName(strNombre);
                        Console.WriteLine("Apellido Paterno:");
                        Console.Write("> ");
                        strLname = Console.ReadLine();
                        cus6.setfLastName(strLname);
                        Console.WriteLine("Apellido Materno:");
                        Console.Write("> ");
                        strMname = Console.ReadLine();
                        cus6.setmLastName(strMname);
                        Console.WriteLine("Direccion:");
                        Console.Write("> ");
                        strDir = Console.ReadLine();
                        cus6.setAddress(strDir);
                        Console.WriteLine("Email:");
                        Console.Write("> ");
                        strEmail = Console.ReadLine();
                        cus6.setEmail(strEmail);
                        int flag;
                        do
                        {
                            flag = 1;
                            try
                            {
                                Console.WriteLine("Telefono");
                                Console.Write("> ");
                                strTelf = Console.ReadLine();

                            }

                            catch (FormatException)
                            {
                                flag = 0;
                                Console.WriteLine("Error !!!, debes ingresar un dato entero!!!");
                            }

                        } while (flag == 0);
                        cus6.setPhoneNumber(strTelf);
                        cus6.setStatus(1);
                        cus6.setRegDate(new DateTime());

                        SalesManager.addCustomer(cus6);
                        Console.WriteLine("===Registro exitoso===");
                        Console.WriteLine("> Ingrese la opci�n: Agregar (n)uevo cliente: n,(t)erminar registro cliente: t");
                        Console.Write("> ");
                        opcion = Console.ReadLine();
                    } while (opcion.CompareTo("n") == 0);
                }
                else if (opcionesCliente == 2) {

                    int id;

                    Console.WriteLine("===ACTUALIZAR CLIENTE===");
                    Console.WriteLine("> Ingrese el codigo del cliente");
                    Console.Write(">");
                    
                    pass = "";
                    do
                    {
                        key = Console.ReadKey(true);

                        // Backspace Should Not Work
                        if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                        {
                            pass += key.KeyChar;
                            Console.Write("*");
                        }
                        else
                        {
                            if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
                            {
                                pass = pass.Substring(0, (pass.Length - 1));
                                Console.Write("\b \b");
                            }
                        }
                    }
                    // Stops Receving Keys Once Enter is Pressed
                    while (key.Key != ConsoleKey.Enter);
                    Console.WriteLine();
                    String nombre;
                    id = Convert.ToInt32(pass);
                    Customer c = SalesManager.getCustomerById(id);
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine("=================================================");
                    Console.WriteLine("=================================================");
                    Console.WriteLine(" Informacion del Cliente");
                    Console.WriteLine("DNI: " + c.getDni());
                    Console.WriteLine("Nombre: " + c.getName());
                    Console.WriteLine("Apellidos: " + c.getfLastName() + "  " + c.getmLastName());
                    Console.WriteLine("Telefono: " + c.getPhoneNumber());
                    Console.WriteLine("Direccion: " + c.getAddress());
                    Console.WriteLine("=================================================");
                    Console.WriteLine("> Modificar Nombre");
                    Console.Write(">");
                    nombre = Console.ReadLine();

                    
                    c.setName(nombre);
                    SalesManager.updateCustomer(c);

                    Console.WriteLine("=================================================");
                }
                else if (opcionesCliente == 3) {

                    Console.WriteLine("===ELIMINAR CLIENTE===");
                    Console.WriteLine("> Ingrese el dni del usuario");
                    Console.Write(">");
                    pass = "";
                    do
                    {
                        key = Console.ReadKey(true);

                        // Backspace Should Not Work
                        if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                        {
                            pass += key.KeyChar;
                            Console.Write("*");
                        }
                        else
                        {
                            if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
                            {
                                pass = pass.Substring(0, (pass.Length - 1));
                                Console.Write("\b \b");
                            }
                        }
                    }
                    // Stops Receving Keys Once Enter is Pressed
                    while (key.Key != ConsoleKey.Enter);
                    Console.WriteLine();
                    
                    SalesManager.deleteCustomer(pass);
                }		
            }while(opcionesCliente!=4);

		}
		else if(opInt==2){ //Operaciones con producto
            String opcionProducto;
            int opcionesProducto;
			if(userRole==0){
                do
                {      
                    Console.WriteLine("> Ud. no puede realizar esta operacion,ingrese el token o llame a su Store Manager");
                    Console.Write("> ");

                    pass = "";
                    do
                    {
                        key = Console.ReadKey(true);

                        // Backspace Should Not Work
                        if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                        {
                            pass += key.KeyChar;
                            Console.Write("*");
                        }
                        else
                        {
                            if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
                            {
                                pass = pass.Substring(0, (pass.Length - 1));
                                Console.Write("\b \b");
                            }
                        }
                    }
                    // Stops Receving Keys Once Enter is Pressed
                    while (key.Key != ConsoleKey.Enter);
                    Console.WriteLine();
                    accessCode = Convert.ToInt32(pass);
                } while (accessCode != 5678); 
			}

            do
            {
                Console.WriteLine("================================================");
                Console.WriteLine(" (1) Registrar  Producto");
                Console.WriteLine(" (2) Actualizar Producto");
                Console.WriteLine(" (3) Eliminar Producto");
                Console.WriteLine(" (4) Terminar");
                Console.WriteLine("=================================================");
                opcionProducto = Console.ReadLine();
                opcionesProducto = Convert.ToInt32(opcionProducto);
            
                if (opcionesProducto == 1)
                {

                    String opcion;
                    do
                    {

                        Console.WriteLine("===REGISTRAR PRODUCTO===");
                        Product newProd = new Product();
                        //BufferedReader Console=new BufferedReader(new InputStreamReader(System.in));
                        String strProd, strDesc, strEan, strPrecio, strCategoria, strMarca, strStock;

                        Console.WriteLine("Nombre:");
                        Console.Write("> ");
                        strProd = Console.ReadLine();
                        newProd.setName(strProd);
                        Console.WriteLine("Descripcion:");
                        Console.Write("> ");
                        strDesc = Console.ReadLine();
                        newProd.setDescription(strDesc);
                        Console.WriteLine("Codigo de barra:");
                        Console.Write("> ");
                        strEan = Console.ReadLine();
                        newProd.setEan(strEan);

                        double priceDoub = 0;
                        int flag;
                        do
                        {
                            flag = 1;
                            try
                            {
                                Console.WriteLine("Precio:");
                                Console.Write("> ");
                                strPrecio = Console.ReadLine();
                                priceDoub = Convert.ToDouble(strPrecio);
                            }

                            catch (FormatException)
                            {
                                flag = 0;
                                Console.WriteLine("Error !!!, debes ingresar un dato double!!!");
                            }

                        } while (flag == 0);

                        newProd.setBasePrice(priceDoub);



                        Console.WriteLine("Categoria:");
                        Console.Write("> ");
                        strCategoria = Console.ReadLine();
                        newProd.setCategory(strCategoria);

                        Console.WriteLine("Marca:");
                        Console.Write("> ");
                        strMarca = Console.ReadLine();
                        newProd.setBrand(strMarca);
                        int stockInt = 0;
                        do
                        {
                            flag = 1;
                            try
                            {
                                Console.WriteLine("Stock:");
                                Console.Write("> ");
                                strStock = Console.ReadLine();
                                stockInt = Convert.ToInt32(strStock);
                            }

                            catch (FormatException)
                            {
                                flag = 0;
                                Console.WriteLine("Error !!!, debes ingresar un dato entero!!!");
                            }
                        } while (flag == 0);

                        newProd.setStock(stockInt);

                        SalesManager.addProduct(newProd);
                        Console.WriteLine("===Registro exitoso===");
                        Console.WriteLine("> Ingrese la opción: Agregar (n)uevo producto: n,(t)erminar registro producto: t");
                        Console.Write("> ");
                        opcion = Console.ReadLine();
                    } while (opcion.CompareTo("n") == 0);

                }
                else if (opcionesProducto == 2) {
                    int id;
                    Console.WriteLine("===ACTUALIZAR PRODUCTO===");
                    Console.WriteLine("> Ingrese codigo del producto");
                    pass = "";
                    do
                    {
                        key = Console.ReadKey(true);

                        // Backspace Should Not Work
                        if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                        {
                            pass += key.KeyChar;
                            Console.Write("*");
                        }
                        else
                        {
                            if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
                            {
                                pass = pass.Substring(0, (pass.Length - 1));
                                Console.Write("\b \b");
                            }
                        }
                    }
                    // Stops Receving Keys Once Enter is Pressed
                    while (key.Key != ConsoleKey.Enter);
                    Console.WriteLine();
                    String strPrecio;
                    double precio=0;
                    id = Convert.ToInt32(pass);

                    Product p = SalesManager.getProductById(id);
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine("=================================================");
                    Console.WriteLine("=================================================");
                    Console.WriteLine(" Informacion del Producto");
                    Console.WriteLine(" Nombre: "+p.getName());
                    Console.WriteLine(" Base Price: " + p.getBasePrice());
                    Console.WriteLine(" Nombre: " + p.getBrand());
                    Console.WriteLine(" Nombre: " + p.getCategory());

                    Console.WriteLine("=================================================");

                    Console.Write(">");
                    int flag;
                    do
                    {
                        flag = 1;
                        try
                        {
                            Console.WriteLine("> Modificar Precio Base. Ingrese nuevo Precio");
                            Console.Write("> ");
                            strPrecio = Console.ReadLine();
                            precio = Convert.ToDouble(strPrecio);
                        }

                        catch (FormatException)
                        {
                            flag = 0;
                            Console.WriteLine("Error !!!, debes ingresar un dato double!!!");
                        }

                    } while (flag == 0);

                    Console.WriteLine("=================================================");

                    p.setBasePrice(precio);
                    SalesManager.updateProduct(p);


                }
                else if (opcionesProducto == 3) {
                    String codigoProd;
                    int codigoProdInt;
                    Console.WriteLine("===ELIMINAR PRODUCTO===");
                    Console.WriteLine(">Ingrese codigo del producto");
                    Console.Write(">");
                    codigoProd = Console.ReadLine();
                    codigoProdInt = Convert.ToInt32(codigoProd);
                    SalesManager.deleteProduct(codigoProdInt);

                }

           }while(opcionesProducto!=4);
            
			
		}
		else if(opInt==3){ //operaciones de cajero
            String opcionCajero;
            int opcionesCajero;
			
		  if(userRole==0){
              do
              {
                  Console.WriteLine("> Ingrese el token o llame a su Store Manager");
                  Console.Write("> ");
                  String code = Console.ReadLine();
                  accessCode = Convert.ToInt32(code);
              } while (accessCode != 5678);
		  }

      do{
          Console.WriteLine("================================================");
          Console.WriteLine(" (1) Registrar  Cajero");
          Console.WriteLine(" (2) Actualizar Cajero");
          Console.WriteLine(" (3) Eliminar Cajero");
          Console.WriteLine(" (4) Terminar");
          Console.WriteLine("=================================================");
          opcionCajero = Console.ReadLine();
          opcionesCajero = Convert.ToInt32(opcionCajero);

          if (opcionesCajero == 1)
          {
              String opcion;
              do
              {
                  Console.WriteLine("===REGISTRAR CAJERO===");
                  String strDni, strNombre, strLname, strMname, strDia, strMes, strAnio;
                  Cashier cash4 = new Cashier();
                  //Asignacion de tienda
                  Store s1 = new Store(); s1.setId(1); s1.setAddress("JvPrado 555, San Isidro");


                  DateTime birthday = new DateTime();

                  Console.WriteLine("Dni");
                  Console.Write("> ");
                  strDni = Console.ReadLine();
                  cash4.setDni(strDni);

                  Console.WriteLine("Nombre:");
                  Console.Write("> ");
                  strNombre = Console.ReadLine();
                  cash4.setName(strNombre);

                  Console.WriteLine("Apellido paterno:");
                  Console.Write("> ");
                  strLname = Console.ReadLine();
                  cash4.setfLastName(strLname);

                  Console.WriteLine("Apellido materno:");
                  Console.Write("> ");
                  strMname = Console.ReadLine();
                  cash4.setmLastName(strMname);


                  Console.WriteLine("Nacimiento: dd /mm/ aa");
                  int diaInt = 0, mesInt = 0, anioInt = 0, flag;
                  do
                  {
                      flag = 1;
                      try
                      {
                          Console.WriteLine("Dia:");
                          Console.Write("> ");
                          strDia = Console.ReadLine();
                          diaInt = Convert.ToInt32(strDia);
                      }

                      catch (FormatException)
                      {
                          flag = 0;
                          Console.WriteLine("Error !!!, debes ingresar un dato entero!!!");
                      }

                  } while (flag == 0);
                  do
                  {
                      flag = 1;
                      try
                      {
                          Console.WriteLine("Mes:");
                          Console.Write("> ");
                          strMes = Console.ReadLine();
                          mesInt = Convert.ToInt32(strMes);
                      }

                      catch (FormatException)
                      {
                          flag = 0;
                          Console.WriteLine("Error !!!, debes ingresar un dato entero!!!");
                      }

                  } while (flag == 0);
                  do
                  {
                      flag = 1;
                      try
                      {
                          Console.WriteLine("Año:");
                          Console.Write("> ");
                          strAnio = Console.ReadLine();
                          anioInt = Convert.ToInt32(strAnio);
                      }

                      catch (FormatException)
                      {
                          flag = 0;
                          Console.WriteLine("Error !!!, debes ingresar un dato entero!!!");
                      }

                  } while (flag == 0);

                  birthday.AddDays(diaInt);
                  birthday.AddMonths(mesInt);
                  birthday.AddYears(anioInt);
                  cash4.setBirthdate(birthday);

                  cash4.setUserCode(66601);
                  cash4.setPassword(1234);
                  cash4.setStore(s1);

                  SalesManager.addCashier(cash4);
                  Console.WriteLine(">Ingrese la opción: Agregar (n)uevo cajero: n, (t)erminar la registro: t");
                  Console.Write("> ");
                  opcion = Console.ReadLine();

              } while (opcion.CompareTo("n") == 0);
          }
          else if (opcionesCajero == 2) {
              Console.WriteLine("===ACTUALIZAR CAJERO===");
          }
          else if (opcionesCajero == 3) {
              String codigoCajero;
              int codigoCajeroInt;
              Console.WriteLine("===ELIMININAR CAJERO===");
              Console.WriteLine(">Ingrese codigo de cajero");
              Console.Write(">");
              codigoCajero = Console.ReadLine();
              codigoCajeroInt = Convert.ToInt32(codigoCajero);
              SalesManager.deleteCashier(codigoCajeroInt);

          }
        }while(opcionesCajero!=4);
			
		}
		else if(opInt==4){
            String opcionVenta;
            int opcionesVenta;
            do{
    

                Console.WriteLine("================================================");
                Console.WriteLine(" (1) Registrar  Venta");
                Console.WriteLine(" (2) Eliminar Venta");
                Console.WriteLine(" (3) Terminar");
                Console.WriteLine("=================================================");
                opcionVenta = Console.ReadLine();
                opcionesVenta = Convert.ToInt32(opcionVenta);

                if (opcionesVenta == 1)
                {
                    Console.WriteLine("======REGISTRAR VENTA===============");
                    do
                    {
                        Console.WriteLine("> Ingrese código del cliente:");
                        Console.Write("> ");
                        scan = Console.ReadLine(); codCli = Convert.ToInt32(scan);
                        if (SalesManager.getCustomerById(codCli) == null)
                            Console.WriteLine("ERROR: El código de cliente que ingreso, no existe");
                    } while (SalesManager.getCustomerById(codCli) == null);
                    Console.WriteLine("> Ciente registrado: " +
                                         SalesManager.getCustomerById(codCli).getName() + " " +
                                         SalesManager.getCustomerById(codCli).getfLastName() + " " +
                                         SalesManager.getCustomerById(codCli).getmLastName());
                    Console.WriteLine("> ");

                    Sale curSale = new Sale(); curSale.setId_sale(200);
                    curSale.setTotalAmmount(0);
                    curSale.setTax(curTax);
                    curSale.setCashier(SalesManager.getCashierById(codCash));
                    curSale.setRegDate(new DateTime());
                    curSale.setRegMachine(5);
                    curSale.setType("contado");

                    int codProd, cant = 0;

                    Console.WriteLine("> Ingrese la opción: Agregar (n)uevo producto: n, (e)liminar producto: e , (t)erminar la venta: t");
                    Console.Write("> ");
                    String opcion = Console.ReadLine();
                    while (opcion.CompareTo("n") == 0 || opcion.CompareTo("e") == 0)
                    {
                        Product prod;
                        //product validation
                        do
                        {
                            Console.WriteLine("> Ingrese código del producto:");
                            Console.Write("> ");
                            scan = Console.ReadLine();
                            codProd = Convert.ToInt32(scan);

                            prod = SalesManager.getProductById(codProd);
                            if (prod == null)
                                Console.WriteLine("Error: El código que usted ingres�, no existe");


                        } while (prod == null);
                        //end of product validation

                        if (opcion.CompareTo("n") == 0)
                        {
                            Console.WriteLine("> " + "Nombre del producto: " + prod.getName()
                                                   + ", P.U: S/. " + prod.getBasePrice()
                                                   + ",Stock disponible: " + prod.getStock() + "unidades");
                            //cant validation

                            do
                            {
                                Console.WriteLine("> Ingrese la cantidad:");
                                Console.Write("> ");
                                scan = Console.ReadLine();
                                cant = Convert.ToInt32(scan);
                                if (cant > prod.getStock())
                                    Console.WriteLine("> ERROR:La cantidad ingresada sobrepasa el stock disponible");
                            } while (cant > prod.getStock());
                            //end of cant validation
                            curSale.addSaleDetail(prod, cant);
                        }
                        else if (opcion.CompareTo("e") == 0)
                        {
                            cant = curSale.getSalesDetailByProduct(prod).getQuantity();
                            curSale.addSaleDetail(prod, -cant);
                        }
                        Console.WriteLine("> Ingrese la opción: Agregar (n)uevo producto: n, (e)liminar producto: e, (t)erminar la venta: t");
                        Console.Write("> ");
                        opcion = Console.ReadLine();
                    }
                    //cash validation
                    double cash = 0.0;
                    do
                    {
                        int flag;
                        do
                        {
                            flag = 1;
                            try
                            {
                                Console.Write("> Ingrese Monto efectivo: ");
                                Console.Write("> ");
                                String ef = Console.ReadLine();
                                cash = Convert.ToDouble(ef);
                            }

                            catch (FormatException)
                            {
                                flag = 0;
                                Console.WriteLine("Error !!!, debes ingresar un dato double!!!");
                            }

                        } while (flag == 0);

                        if (cash < curSale.getTotalAmmount())
                            Console.WriteLine("> Error: El monto ingresado es menor que el monto total de la venta");
                    } while (cash < curSale.getTotalAmmount());
                    //end of cash validation

                    SalesManager.addSale(curSale);
                    Console.WriteLine("> ===============Fin de la venta===============");
                    Console.WriteLine("> =============Reporte de la venta=============");//Ticket de venta
                    Console.WriteLine("> .............................................");
                    if (userRole == 0)
                        Console.WriteLine("> " + curSale.getCashier().getStore().getAddress());
                    else
                        Console.WriteLine("Store #");
                    Console.WriteLine("> BOOLEAN S.A.");
                    List<SalesDetail> deList = curSale.showSaleDetail();
                    Console.WriteLine();
                    Console.WriteLine("> Fecha:" + curSale.getRegDate());
                    Console.WriteLine("> ");
                    Console.WriteLine("> Producto   Precio     Cantidad");
                    for (int i = 0; i < deList.Count(); i++)
                    {
                        Console.Write("> " + deList.ElementAt(i).getProduct().getName());
                        Console.Write("   S/. " + deList.ElementAt(i).getProduct().getBasePrice());
                        Console.Write("       " + deList.ElementAt(i).getQuantity());
                        Console.WriteLine();
                    }
                    Console.WriteLine("> TOTAL: S/." + curSale.getTotalAmmount());
                    Console.WriteLine("> ");
                    Console.WriteLine("> EFECTIVO: S/." + cash);
                    Console.WriteLine("> CAMBIO: S/." + (cash - curSale.getTotalAmmount()));
                    Console.WriteLine("> ");
                    if (userRole == 0)
                        Console.WriteLine("> CAJA #" + curSale.getRegMachine() + "-" + curSale.getCashier().getName());
                    else
                        Console.WriteLine("> CAJA #" + curSale.getRegMachine() + "-" + "Store Manager");
                    Console.WriteLine();
                    Console.WriteLine("=================================================");


                }
                else if (opcionesVenta == 2) { }
            }while(opcionesVenta!=3);
		}
          if (opInt == 5) {
              String opcionTerminal;
              int opcionesTerminal;

              if (userRole == 0)
              {
                  do
                  {
                      Console.WriteLine("> Ingrese el token o llame a su Store Manager");
                      Console.Write("> ");
                      String code = Console.ReadLine();
                      accessCode = Convert.ToInt32(code);
                  } while (accessCode != 5678);
              }


             do{
                Console.WriteLine("================================================");
                Console.WriteLine(" (1) Registrar  terminal");
                Console.WriteLine(" (2) Eliminar terminal");
                Console.WriteLine(" (3) Terminar");
                Console.WriteLine("=================================================");
                opcionTerminal = Console.ReadLine();
                opcionesTerminal = Convert.ToInt32(opcionTerminal);
                if (opcionesTerminal == 1) {
                    String name;
                    Console.WriteLine("======REGISTRAR TERMINAL===============");
                    CashierTerminal terminal = new CashierTerminal();
                    Console.WriteLine(">Ingrese nombre de la terminal");
                    Console.Write("> ");
                    name = Console.ReadLine();
                    terminal.setMachineName(name);
                    terminal.setMontoFinal(0.0);
                    terminal.setMontoInicial(0.0);
                    SalesManager.addCashierTerminal(terminal);
                }
                else if (opcionesTerminal == 2) {
                    int id;
                    String idTerminal;
                    Console.WriteLine("======ELIMINAR TERMINAL===============");
                    Console.WriteLine(">Ingrese codigo de la terminal");
                    Console.Write("> ");
                    idTerminal = Console.ReadLine();
                    id=Convert.ToInt32(idTerminal);
                    SalesManager.deleteCashierTerminal(id);
                }

             }while(opcionesTerminal!=3);

          }
		
		}while(opInt!=6);
		userRole=0;
		
	}
	
	
	/*
	 * cashier=0
	 * storeManager= 1
	 * */
	static int userRole=0;


        [STAThread]
        static void Main(string[] args)
        {
            /*
            SalesManager.ReloadCustomersDB("CustomersDB.xml");
            SalesManager.ReloadProductsDB("ProductsDB.xml");
            //cashiers
            Cashier cash1 = new Cashier(); cash1.setId(17001);
            Cashier cash2 = new Cashier(); cash2.setId(17002);
            Cashier cash3 = new Cashier(); cash3.setId(17003);

            fillCashierData(cash1, cash2, cash3);

            SalesManager.addCashier(cash1);
            SalesManager.addCashier(cash2);
            SalesManager.addCashier(cash3);
            //Store Manager
            StoreManager cash4 = new StoreManager();
            cash4.setId(17004);
            fillStoreManagerData(cash4);
            SalesManager.addStoreManager(cash4);


            //----->end imaginary database upload


            showInvoice();

            SalesManager.PersistCustomersDB("CustomersDB.xml");
            SalesManager.PersistProductsDB("ProductsDB.xml");
            Console.ReadLine(); //--->          
            
             */

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainWindow());
             
        }
    /*
    static void fillCustomerData(Customer cus1, Customer cus2, Customer cus3, Customer cus4, Customer cus5){
		    DateTime dateNow = new DateTime();
		
		    cus1.setDni("17444444"); cus2.setDni("17555555"); cus3.setDni("17666666"); cus4.setDni("17888888"); cus5.setDni("17999999");
		    cus1.setName("John"); cus2.setName("Camila"); cus3.setName("Dan"); cus4.setName("Dave"); cus5.setName("Clau");
		    cus1.setfLastName("Perez"); cus2.setfLastName("Churchill"); cus3.setfLastName("Zuckerberg"); cus4.setfLastName("Johnson"); cus5.setfLastName("Dorian");
		    cus1.setmLastName("Flores"); cus2.setmLastName("Flores"); cus3.setmLastName("Flores"); cus4.setmLastName("Flores"); cus5.setmLastName("Flores");
		    cus1.setAddress("Aviacion 3344, San Borja");
		    cus2.setAddress("JvPrado 555, San Isidro");
		    cus3.setAddress("AvMexico 666, Cercado de Lima");
		    cus4.setAddress("Arequipa 669, Lince");
		    cus5.setAddress("Larco 517, Miraflores");
		    cus1.setEmail("jonnycash@gmail.com"); cus2.setEmail("camicamin@gmail.com"); cus3.setEmail("dandendin@gmail.com"); cus4.setEmail("davethebarbarian@gmail.com"); cus5.setEmail("clauaud@gmail.com");
		    cus1.setPhoneNumber("225987321"); cus2.setPhoneNumber("22522222"); cus3.setPhoneNumber("225112233"); cus4.setPhoneNumber("225999888"); cus5.setPhoneNumber("225246808");
		    cus1.setStatus(1);cus2.setStatus(1);cus3.setStatus(1);cus4.setStatus(1);cus5.setStatus(1);
		    cus1.setRegDate(dateNow);cus2.setRegDate(dateNow);cus3.setRegDate(dateNow);cus4.setRegDate(dateNow);cus5.setRegDate(dateNow);
	}
	
	static void fillProductData(Product pro1,Product pro2,Product pro3,Product pro4,Product pro5,
			Product  pro6,Product pro7,Product pro8,Product pro9,Product pro10){
		
		    pro1.setName("queso"); pro2.setName("yogurt"); pro3.setName("mantequilla"); pro4.setName("pan"); pro5.setName("desodorante");
		    pro6.setName("pilas"); pro7.setName("soda"); pro8.setName("fideos"); pro9.setName("arroz"); pro10.setName("shampoo");
		    pro1.setDescription("queso cheddar");pro6.setDescription("pilas recargables");
		    pro2.setDescription("yogurt cremoso");pro7.setDescription("gaseosa gasificada");
		    pro3.setDescription("mantequilla de vaca cautiva");pro8.setDescription("fideos para sopa");
		    pro4.setDescription("pan de ancash");pro9.setDescription("arroz blanco procesado");
		    pro5.setDescription("desodorante para piel");pro10.setDescription("shampoo para bebes");
		    pro1.setEan("2233445500");pro6.setEan("2233445569");
		    pro2.setEan("2233445599");pro7.setEan("2233445522");
		    pro3.setEan("2233445588");pro8.setEan("2233445523");
		    pro4.setEan("2233445577");pro9.setEan("2233445525");
		    pro5.setEan("2233445555");pro10.setEan("2233445517");
		    pro1.setBasePrice(5.30);pro6.setBasePrice(5.50);
		    pro2.setBasePrice(6.69);pro7.setBasePrice(3.20);
		    pro3.setBasePrice(3.30);pro8.setBasePrice(2.20);
		    pro4.setBasePrice(1.20);pro9.setBasePrice(3.50);
		    pro5.setBasePrice(10.50);pro10.setBasePrice(9.69);
		    pro1.setCategory("comida");pro6.setCategory("accesorios");
		    pro2.setCategory("comida");pro7.setCategory("bebidas");
		    pro3.setCategory("comida");pro8.setCategory("comida");
		    pro4.setCategory("comida");pro9.setCategory("comida");
		    pro5.setCategory("aseo");pro10.setCategory("aseo");
		    pro1.setBrand("Vaquitacs");pro6.setBrand("Magneto");
		    pro2.setBrand("Vaquitacs");pro7.setBrand("Santogrial");
		    pro3.setBrand("Vaquitacs");pro8.setBrand("Granjal");
		    pro4.setBrand("Bromater");pro9.setBrand("Granjal");
		    pro5.setBrand("Oloroso");pro10.setBrand("Oloroso");
		    pro1.setStock(30);pro6.setStock(20);
		    pro2.setStock(42);pro7.setStock(30);
		    pro3.setStock(30);pro8.setStock(55);
		    pro4.setStock(10);pro9.setStock(42);
		    pro5.setStock(17);pro10.setStock(51);		
		
	}
	
	//@SuppressWarnings("deprecation")
	static void fillCashierData(Cashier cash1,Cashier cash2,Cashier cash3){
		Store s1= new Store();s1.setId(1);s1.setAddress("JvPrado 555, San Isidro");//New store created
		
		//@SuppressWarnings("deprecation")
		DateTime birthday = new DateTime(1990,07,30);
		cash1.setName("Leslie"); cash1.setfLastName("Hoso"); cash1.setmLastName("Moto");
		cash1.setBirthdate(birthday); cash1.setDni("55517171");
		
		cash1.setUserCode(66601); cash1.setPassword(1234);cash1.setStore(s1);
		
		birthday.AddDays(-15); birthday.AddMonths(-2); birthday.AddYears(1);
		cash2.setName("Lola"); cash2.setfLastName("Mena"); cash2.setmLastName("Black");
		cash2.setBirthdate(birthday); cash2.setDni("55517171");
		
		cash2.setUserCode(66601); cash2.setPassword(1234);cash2.setStore(s1);
		
		birthday.AddDays(-13); birthday.AddMonths(-5); birthday.AddYears(-1);
		cash3.setName("Lulu"); cash3.setfLastName("Carr"); cash3.setmLastName("Lock");
		cash3.setBirthdate(birthday); cash3.setDni("55517171");
		
		cash3.setUserCode(66601); cash3.setPassword(1234);cash3.setStore(s1);	
		
	}
    static void fillStoreManagerData(StoreManager cash3)
    {
        Store s1 = new Store(); s1.setId(1); s1.setAddress("JvPrado 555, San Isidro");//New store created
        DateTime birthday = new DateTime();
        birthday.AddDays(17); birthday.AddMonths(2); birthday.AddYears(1989);
        cash3.setName("Claudia"); cash3.setfLastName("Baldeon "); cash3.setmLastName("Lock");
        cash3.setBirthdate(birthday); cash3.setDni("55517171");
        cash3.setToken(5678);
        cash3.setUserCode(66601); cash3.setPassword(5678); cash3.setStore(s1);

    }
     */

    }
}
